<template>
    <form>
        <table>
            <tbody>
                <tr>
                    <td><label for="">书名：</label></td>
                    <td><input type="text" v-model="book.bookName"></td>
                </tr>
                <tr>
                    <td><label for="">作者：</label></td>
                    <td><input type="text" v-model="book.author"></td>
                </tr>
                <tr>
                    <td><input type="button" value="保存" @click="btnSave()"></td>
                    <td><input type="button" value="取消" @click="btnBack()"></td>
                </tr>
            </tbody>
        </table>
    </form>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'

const router = new useRouter()
const route = new useRoute()

const url = 'http://localhost:8000'

const book = ref({
    bookName: '',
    author: ''
})

onMounted(async () => {
    const id = route.params.id || 0
    if (id) {
        const data = await axios.get(`${url}/book/${id}`)
        book.value = data.data.data
    }
})

async function btnSave() {
    const id = route.params.id || 0
    if (id) {
        await axios.put(`${url}/book/${id}`, book.value)
    } else {
        await axios.post(`${url}/book`, book.value)
    }
    router.push('/book')
}

function btnBack() {
    router.push('/book')
}

function btnQuery() {
    const trimKeyword = keyword.value.trim()
    const data = axios.get(`${url}/book?keyword=${trimKeyword}`)
    bookList.value = data.data.data
}

</script>